package com.nbcio.modules.erp.report.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbcio.common.core.domain.R;
import com.nbcio.modules.erp.voucher.domain.ErpVoucher;
import com.nbcio.modules.erp.voucher.domain.ErpVoucherEntry;
import com.nbcio.modules.erp.voucher.mapper.ErpAccountMapper;
import com.nbcio.modules.erp.voucher.mapper.ErpVoucherEntryMapper;
import com.nbcio.modules.erp.voucher.mapper.ErpVoucherMapper;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 财务报表控制器
 */
@RestController
@RequestMapping("/erp/report/finance")
public class ErpFinanceReportController {

    @Resource
    private ErpVoucherMapper voucherMapper;
    @Resource
    private ErpVoucherEntryMapper voucherEntryMapper;
    @Resource
    private ErpAccountMapper accountMapper;

    /**
     * 凭证列表查询（分页）
     */
    @GetMapping("/voucher/page")
    public R<Page<ErpVoucher>> pageVoucher(
            @RequestParam(required = false) String voucherNo,
            @RequestParam(required = false) LocalDate startDate,
            @RequestParam(required = false) LocalDate endDate,
            @RequestParam(required = false) String billType,
            @RequestParam(required = false) Long billId,
            @RequestParam(defaultValue = "1") Long pageNum,
            @RequestParam(defaultValue = "10") Long pageSize) {
        LambdaQueryWrapper<ErpVoucher> qw = new LambdaQueryWrapper<>();
        if (voucherNo != null && !voucherNo.isEmpty()) {
            qw.like(ErpVoucher::getVoucherNo, voucherNo);
        }
        if (startDate != null && endDate != null) {
            qw.between(ErpVoucher::getVoucherDate, startDate, endDate);
        }
        if (billType != null && !billType.isEmpty()) {
            qw.eq(ErpVoucher::getBillType, billType);
        }
        if (billId != null) {
            qw.eq(ErpVoucher::getBillId, billId);
        }
        qw.eq(ErpVoucher::getStatus, "POSTED");
        qw.orderByDesc(ErpVoucher::getVoucherDate, ErpVoucher::getVoucherNo);
        
        Page<ErpVoucher> page = new Page<>(pageNum, pageSize);
        return R.ok(voucherMapper.selectPage(page, qw));
    }

    /**
     * 凭证明细查询
     */
    @GetMapping("/voucher/{voucherId}/entries")
    public R<List<ErpVoucherEntry>> getVoucherEntries(@PathVariable("voucherId") Long voucherId) {
        LambdaQueryWrapper<ErpVoucherEntry> qw = new LambdaQueryWrapper<>();
        qw.eq(ErpVoucherEntry::getVoucherId, voucherId);
        qw.orderByAsc(ErpVoucherEntry::getEntryNo);
        return R.ok(voucherEntryMapper.selectList(qw));
    }

    /**
     * 科目余额汇总（简化版）
     */
    @GetMapping("/account/balance")
    public R<List<Map<String, Object>>> accountBalance(
            @RequestParam(required = false) Long accountId,
            @RequestParam(required = false) LocalDate startDate,
            @RequestParam(required = false) LocalDate endDate) {
        LambdaQueryWrapper<ErpVoucher> voucherQw = new LambdaQueryWrapper<>();
        if (startDate != null && endDate != null) {
            voucherQw.between(ErpVoucher::getVoucherDate, startDate, endDate);
        }
        voucherQw.eq(ErpVoucher::getStatus, "POSTED");
        List<ErpVoucher> vouchers = voucherMapper.selectList(voucherQw);
        
        if (vouchers.isEmpty()) {
            return R.ok(List.of());
        }
        
        List<Long> voucherIds = vouchers.stream().map(ErpVoucher::getVoucherId).collect(Collectors.toList());
        LambdaQueryWrapper<ErpVoucherEntry> entryQw = new LambdaQueryWrapper<>();
        entryQw.in(ErpVoucherEntry::getVoucherId, voucherIds);
        if (accountId != null) {
            entryQw.eq(ErpVoucherEntry::getAccountId, accountId);
        }
        List<ErpVoucherEntry> entries = voucherEntryMapper.selectList(entryQw);
        
        // 按科目汇总
        Map<Long, Map<String, Object>> balanceMap = new HashMap<>();
        for (ErpVoucherEntry entry : entries) {
            Long accId = entry.getAccountId();
            balanceMap.computeIfAbsent(accId, k -> {
                Map<String, Object> map = new HashMap<>();
                map.put("accountId", accId);
                map.put("debitTotal", BigDecimal.ZERO);
                map.put("creditTotal", BigDecimal.ZERO);
                return map;
            });
            Map<String, Object> map = balanceMap.get(accId);
            if ("DEBIT".equals(entry.getDcFlag())) {
                BigDecimal debit = (BigDecimal) map.get("debitTotal");
                map.put("debitTotal", debit.add(entry.getAmount()));
            } else {
                BigDecimal credit = (BigDecimal) map.get("creditTotal");
                map.put("creditTotal", credit.add(entry.getAmount()));
            }
        }
        
        List<Map<String, Object>> result = balanceMap.values().stream()
                .map(map -> {
                    BigDecimal debit = (BigDecimal) map.get("debitTotal");
                    BigDecimal credit = (BigDecimal) map.get("creditTotal");
                    BigDecimal balance = debit.subtract(credit);
                    map.put("balance", balance);
                    map.put("balanceDirection", balance.compareTo(BigDecimal.ZERO) >= 0 ? "DEBIT" : "CREDIT");
                    return map;
                })
                .collect(Collectors.toList());
        
        return R.ok(result);
    }
}

